<?php
// +------------------------------------------------+
// | http://www.cjango.com                          |
// +------------------------------------------------+
// | 修复BUG不是一朝一夕的事情，等我喝醉了再说吧！  |
// +------------------------------------------------+
// | Author: 小陈叔叔 <Jason.Chen[cjango.com]>      |
// +------------------------------------------------+
/**
 * 控制器类
 */

class Controller {
	
    protected $tVar     =   array();
	
	function __construct() {
		if(method_exists($this,'_init'))
			$this->_init();
	}

	/**
	 * 模板变量赋值
	 */
	public function assign($name,$value=''){
		if(is_array($name)) {
			$this->tVar   =  array_merge($this->tVar,$name);
		}else {
			$this->tVar[$name] = $value;
		}
	}

	/**
	 * 显示模板
	 */
	public function display($template = '') {
		$baseDir = APP_PATH.MODULE.'/Tpl/';
		$sufix   = '.html';
		if (empty($template)) {
			$tpl = $baseDir . CONTROLLER.'/'.ACTION . $sufix;
		} else {
			if (!strpos($template, '/')) {
				$baseDir .= CONTROLLER .'/';
			}
			$tpl = $baseDir . $template . $sufix;
		}
		if (!is_file($tpl)) {
			throw new Exception("Template File Not exists!", 1);
		}
		// 解析模板
		$content = $this->fetch($tpl);
		// 模板渲染输出
		$this->render($content);
	}

	/**
	 * 模板渲染输出
	 */
	private function render($content) {
		// 网页字符编码
		header("Content-type:text/html;charset=utf-8");
		header("Cache-control: private");  // 页面缓存控制
		header('X-Powered-By:C.Jango');
		// 输出模板文件
		echo $content;
	}

	/**
	 * 解析模板
	 */
	public function fetch($template) {
		ob_start();
		ob_implicit_flush(0);
		// 使用PHP原生模板
		extract($this->tVar, EXTR_OVERWRITE);
		include $template;
		$content = ob_get_clean();
		return $content;
	}

}